#!/usr/bin/env bash

################################################################################
#
# Copyright (C) 2013  Artur Tolstenco
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 
################################################################################

# =============================================================================
#
# Author:       Artur Tolstenco
# Date:		    15/05/2013
# Description:	This script creates (or deletes) a specific mysql user and its 
#               two databses 
#               After the creation of databases this script populates both
#		        databases using the files present in the folder
#
# =============================================================================

CURRENT_DIR=$(dirname "$0")
EXPECTED_ARGS=2
CLEAN_EXPECTED_ARGS=6
CREATE_EXPECTED_ARGS=12

PAR_CREATE='create'
PAR_CLEAN='clean'

PAR_DEPLOY_ON_DIONE='dione'
PAR_DEPLOY_ON_LOCAL='local'

PAR_ALL='all'
PAR_CREATE_USER='create_user'
PAR_POPULATION='populate'


# constants for dione
DB_ROOT_ON_DIONE='root'
DB_ROOT_PWD_ON_DIONE='random85'
DB_HOST_ON_DIONE='localhost'

# constants for local machine
DB_ROOT_ON_LOCAL='root'
DB_ROOT_PWD_ON_LOCAL='toor'
DB_HOST_ON_LOCAL='localhost'

# current deploy configuration - will be modified
DB_ROOT=''
DB_ROOT_PWD=''
DB_HOST=''


# PRIVATE FUNCTIONS ############################################################

# checks if the database population files exists
function check_files() {
    if [ ! -f $RS_DB_SCHEMA ] || [ ! -f $RS_DB_DATA ]; then
        echo 'The population files for "'$RS_DATABASE'" database does not exist'
        exit 1
    fi

    if [ ! -f $DATA_DB_SCHEMA ] || [ ! -f $DATA_DB_DATA ]; then
        echo 'The population files for "'$DATA_DATABASE'" database does not exist'
        exit 1
    fi
}

# checks if there was an error during execution of previous comand 
# and prints the $1 message
function check_error() {
    if [ $? -gt 0 ]; then
		echo $1
		exit 1
	fi
}

function set_deployment_environment() {
    case $1 in
        $PAR_DEPLOY_ON_DIONE)
            DB_ROOT=$DB_ROOT_ON_DIONE
            DB_ROOT_PWD=$DB_ROOT_PWD_ON_DIONE
            DB_HOST=$DB_HOST_ON_DIONE
            ;;
        $PAR_DEPLOY_ON_LOCAL)
            DB_ROOT=$DB_ROOT_ON_LOCAL
            DB_ROOT_PWD=$DB_ROOT_PWD_ON_LOCAL
            DB_HOST=$DB_HOST_ON_LOCAL
            ;;
        *)
            echo 'Unrecognized parameter. Allowed parameters: '$PAR_DEPLOY_ON_DIONE', '$PAR_DEPLOY_ON_LOCAL
            exit 1
    esac
}

function create_user() {
    bash $CURRENT_DIR/db_user.sh create $DB_ROOT $DB_ROOT_PWD $DB_HOST \
	                                     $DB_USER $DB_USER_PWD \
	                                     $RS_DATABASE $DATA_DATABASE
    check_error 'Error creating the new user or its databases...'
	echo 'Created the new user and its databases successfuly'
}

function populate() {
    check_files
    php $CURRENT_DIR/load.mysql.php --data_instance $DATA_INSTANCE \
                      --rs_dbschema $RS_DB_SCHEMA \
                      --rs_dbdata $RS_DB_DATA \
                      --rs_withdata \
                      --data_dbschema $DATA_DB_SCHEMA \
                      --data_dbdata $DATA_DB_DATA \
                      --data_withdata
    check_error 'Error during the population of databases...'
    echo 'Databases populated successfully'
    
    echo
    echo '================================================================================'
    echo 'The database connection params must be edited in the application.ini and config.ini (in the module):'
    echo 'username = '$DB_USER
    echo 'password = '$DB_USER_PWD
    echo 'host = '$DB_HOST
    echo 'dbname = '$RS_DATABASE
    echo 'or'
    echo 'dbname = '$DATA_DATABASE
    echo '================================================================================'
    echo
}

function all() {
    create_user
    populate
}

function create() {
    case $1 in
        $PAR_CREATE_USER)
            create_user
            ;;
        $PAR_POPULATION)
            populate
            ;;
        $PAR_ALL)
            all
            ;;
        *)
            echo 'Unrecognized parameter. Allowed parameters: '$PAR_ALL', '$PAR_CREATE_USER', '$PAR_POPULATION
            exit 1
    esac
}


function clean() {
    bash $CURRENT_DIR/db_user.sh delete $DB_ROOT $DB_ROOT_PWD $DB_HOST \
	                                     $DB_USER $DB_USER_PWD \
	                                     $RS_DATABASE $DATA_DATABASE
    check_error 'Error deleting the user or its databases...'
	echo 'The mysql db user and its database was deleted successfully'
}

################################################################################


# MAIN #########################################################################

if [ $# -lt $EXPECTED_ARGS ]; then
    echo 'Error: some arguments are missing'
	echo 'Usage: '$(basename $0)' '$PAR_CLEAN' '$PAR_DEPLOY_ON_DIONE'|'$PAR_DEPLOY_ON_LOCAL' db_user db_user_pwd rs_database data_database'
    echo 'Usage: '$(basename $0)' '$PAR_CREATE\
	                                       $PAR_DEPLOY_ON_DIONE'|'$PAR_DEPLOY_ON_LOCAL\
	                                       $PAR_ALL'|'$PAR_CREATE_USER'|'$PAR_POPULATION\
	                                       'db_user db_user_pwd data_instance rs_database data_database rs_db_schema rs_db_data data_db_schema data_db_data'
	exit 1
fi

set_deployment_environment $2

case $1 in
    $PAR_CLEAN)
        if [ $# -ne $CLEAN_EXPECTED_ARGS ]; then
	        echo 'Error: some arguments are missing'
	        echo 'Usage: '$(basename $0)' '$PAR_CLEAN' '$PAR_DEPLOY_ON_DIONE'|'$PAR_DEPLOY_ON_LOCAL' db_user db_user_pwd rs_database data_database'
	        exit 1
        fi
        # mysql user to delete
        DB_USER=$3
        DB_USER_PWD=$4
        
        # the two databases to delete
        RS_DATABASE=$5
        DATA_DATABASE=$6
        
        clean
        ;;
    $PAR_CREATE)
        if [ $# -ne $CREATE_EXPECTED_ARGS ]; then
	        echo 'Error: some arguments are missing'
	        echo 'Usage: '$(basename $0)' '$PAR_CREATE\
	                                       $PAR_DEPLOY_ON_DIONE'|'$PAR_DEPLOY_ON_LOCAL\
	                                       $PAR_ALL'|'$PAR_CREATE_USER'|'$PAR_POPULATION\
	                                       'db_user db_user_pwd data_instance rs_database data_database rs_db_schema rs_db_data data_db_schema data_db_data'
	        exit 1
        fi
        
        PARAM_TO_CREATE=$3
        
        # because of limited parameters number allowed in the 
        # bash script... use the shift command
        
        # mysql user to create
        DB_USER=$4
        shift
        
        DB_USER_PWD=$4
        shift
        
        # the specific resource server instantiation
        DATA_INSTANCE=$4
        shift
        
        # the two databases to create for this resource server instantiation
        RS_DATABASE=$4
        shift
        DATA_DATABASE=$4
        shift

        # the $RS_DATABASE population script files
        RS_DB_SCHEMA=$4
        shift
        RS_DB_DATA=$4
        shift

        # the $DATI_DATABASE population script files
        DATA_DB_SCHEMA=$4
        shift
        DATA_DB_DATA=$4
        shift
        
        create $PARAM_TO_CREATE
        ;;
    *)
        echo 'Unrecognized parameter. Allowed parameters: '$PAR_CREATE', '$PAR_CLEAN
esac

exit 0
